package com.oglvip.business.extend.auth;

import com.google.common.collect.Lists;
import com.oglvip.business.consts.common.Consts;
import com.oglvip.business.remote.service.entity.StoreAccount;
import com.oglvip.business.util.CookieHolder;
import com.oglvip.business.util.CookieUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.RememberMeServices;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @auther hanchao
 * @date 2016/12/10 14:18
 */
public class RememberMeService implements RememberMeServices {
    @Override
    public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
        String key = CookieUtils.getCookieValue(request, Consts.REMEMBER_COOKIE);
        if(key != null){
            StoreAccount account = CookieHolder.get(key);
            if(account != null){
                List<SimpleGrantedAuthority> authorities = null;
                if(account.getStatus() == 1){
                    authorities = Lists.newArrayList(new SimpleGrantedAuthority(Consts.ROLE_PREFIX + Consts.USER));
                }else if(account.getStatus() == 0){
                    throw new AuthenticationServiceException("您的审核已经提交，请耐心等待！");
                }else{
                    authorities = Lists.newArrayList(new SimpleGrantedAuthority(Consts.ROLE_PREFIX + Consts.USER_UNREVIEW));
                }
                return new RememberMeAuthenticationToken(Consts.REMEMBER_COOKIE,account,authorities);
            }
        }
        return null;
    }

    @Override
    public void loginFail(HttpServletRequest request, HttpServletResponse response) {

    }

    @Override
    public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {

    }
}
